package ml.classification.filter;

import java.util.ArrayList;

public class PseudoGaussianVotingFilter extends PostProcessingFilter {
	private final boolean isSpeech;

	public PseudoGaussianVotingFilter(final int n, final int iterations,
			final boolean isSpeech) {
		super();
		this.n = n;
		this.iterations = iterations;
		this.isSpeech = isSpeech;
	}

	@Override
	public ArrayList<Integer> apply(final ArrayList<Integer> list) {
		final ArrayList<Integer> newList = new ArrayList<>();
		ArrayList<Integer> currentList = list;
		double votedMax;
		double votedCurrent;

		for (int i = 0; i < iterations; i++) {
			for (int j = 0; j < currentList.size(); j++) {
				votedMax = 0;
				votedCurrent = 0;
				for (int k = j - n; k <= j + n; k++) {
					if (k >= 0 && k < currentList.size()) {
						if (currentList.get(k) == 1) {
							votedCurrent += 1 / Math
									.sqrt((Math.abs(k - j) + 1));
						}
						votedMax += 1 / Math.sqrt((Math.abs(k - j) + 1));
					}
				}
				if (isSpeech) {
					if (votedCurrent > votedMax / 2) {
						newList.add(j, 1);
					} else {
						newList.add(j, 0);
					}
				} else {
					if (votedCurrent > votedMax / 2) {
						newList.add(j, 1);
					} else {
						newList.add(j, 0);
					}
				}

			}
			currentList = new ArrayList<>();
			for (final Integer x : newList) {
				currentList.add(x);
			}
		}
		return currentList;
	}

	@Override
	public String getFilterName() {
		return "PseudoGaussianVotingFilter";
	}
}
